package com.maltys.backtracking;

import java.util.ArrayList;
import java.util.List;

/**
 * @author malty
 * @link <a href="https://leetcode.cn/problems/combination-sum/description/">组合总数2</a>
 */
public class CombinationsSum {
    public List<List<Integer>> combinationSum(int[] candidates, int target) {
        List<List<Integer>> res = new ArrayList<>();
        backTracing(candidates, 0, target, 0, new ArrayList<>(), res);
        return res;
    }

    private void backTracing(int[] candidates, int idx, int target, int sum, List<Integer> list, List<List<Integer>> res) {
        if (sum == target) {
            res.add(new ArrayList<>(list));
            return;
        }

        if (sum > target) {
            return;
        }

        for (int i = idx; i < candidates.length; i++) {
            if (candidates[i] + sum > target) {
                continue;
            }
            list.add(candidates[i]);
            backTracing(candidates, i, target, sum + candidates[i], list, res);
            list.remove(list.size() - 1);
        }
    }

    public static void main(String[] args) {
        CombinationsSum combinationSum = new CombinationsSum();
        List<List<Integer>> lists = combinationSum.combinationSum(new int[]{8, 7, 4, 3}, 11);
        lists.forEach(System.out::println);
    }
}
